package com.luatos.iot.regproxy.module;

import java.util.HashMap;
import java.util.Map;

import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.lang.util.Regex;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;

import com.github.cm.heclouds.onenet.studio.api.IotClient;
import com.github.cm.heclouds.onenet.studio.api.IotProfile;
import com.github.cm.heclouds.onenet.studio.api.entity.common.CreateDeviceRequest;
import com.github.cm.heclouds.onenet.studio.api.entity.common.CreateDeviceResponse;
import com.github.cm.heclouds.onenet.studio.api.entity.common.QueryDeviceDetailRequest;
import com.github.cm.heclouds.onenet.studio.api.entity.common.QueryDeviceDetailResponse;
import com.github.cm.heclouds.onenet.studio.api.exception.IotClientException;
import com.github.cm.heclouds.onenet.studio.api.exception.IotServerException;

@At("/reg")
@Fail("http:500")
@IocBean
public class OnenetIotRegModule {

	private static Log log = Logs.get();

	@Inject
	protected PropertiesProxy conf;
	
	protected Map<String, IotClient> clients = new HashMap<>();

	@At
	@Ok("json:tidy")
	public NutMap onenet(String dev, String key, String sign, String ranstr) {
		// 首先, 检查必要的参数
		if (Strings.isBlank(dev) || Strings.isBlank(key)) {
			log.debug("miss dev/key/sign/ranstr");
			return new NutMap("msg", "miss dev/key/sign");
		}
		if (!Regex.match("^[a-zA-z0-9]{10,20}", dev)) {
			log.info("非法的设备名称" + dev);
			return new NutMap("msg", "bad dev name");
		}
		// 获取项目的accessKey
		String accessKey = conf.get("luatos.regproxy.onenet." + key + ".accessKey");
		String userId = conf.get("luatos.regproxy.onenet." + key + ".userId");
		// 计算签名, md5算法应该是所有设备都能支持的
//		String mysign = Lang.md5(dev + key + Strings.sBlank(ranstr));
//		if (!mysign.equalsIgnoreCase(sign)) {
//			log.debugf("sign not match expect %s but %s", mysign, sign);
//			return new NutMap("msg", "sign not match");
//		}
		if (Strings.isBlank(accessKey) || Strings.isBlank(userId)) {
			return new NutMap("msg", "no such project");
		}

		// 初始化SDK客户端
		IotClient client = clients.get(accessKey);
		if (client == null) {
			IotProfile profile = new IotProfile();
			profile.accessKey(accessKey);
			profile.userId(userId);
			client = IotClient.create(profile);
			clients.put(accessKey, client);
		}
		
		// 尝试创建
		try {
			CreateDeviceRequest cdr = new CreateDeviceRequest();
			cdr.setDeviceName(dev);
			cdr.setProductId(key);
			CreateDeviceResponse cdr_resp = client.sendRequest(cdr);
			if (cdr_resp.getSecKey() != null) {
				return new NutMap("secret", cdr_resp.getSecKey());
			}
		} catch (IotClientException | IotServerException e) {
			//log.info("error", e);
		}

		// 查询历史数据
		QueryDeviceDetailRequest cdd_req = new QueryDeviceDetailRequest();
		cdd_req.setDeviceName(dev);
		cdd_req.setProductId(key);
		try {
			QueryDeviceDetailResponse cdd_resp = client.sendRequest(cdd_req);
			if (cdd_resp.getSecKey() != null) {
				return new NutMap("secret", cdd_resp.getSecKey());
			}
		} catch (IotClientException | IotServerException e) {
			log.info("error", e);
		}
		return new NutMap("msg", "server error");
		
//		Request req = Request.create("https://api.heclouds.com/mqtt/v1/devices/reg", METHOD.POST);
//		req.setData(Json.toJson(new NutMap("name", dev), JsonFormat.full()));
//		Header headers = Header.create();
//		headers.asJsonContentType();
//		req.setHeader(headers);

//		// version=2018-10-31&res=products%2F123123&et=1537255523&method=sha1&sign=ZjA1NzZlMmMxYzIOTg3MjBzNjYTI2MjA4Yw%3D
//		long timenow = System.currentTimeMillis() / 1000 + 30; // 当前时间+30秒
//		String tmp = "version=2018-10-31&res=products%2F" + key + "&et=" + timenow + "&method=sha1&sign=";
//		String strForSign = "" + timenow + '\n' + "sha1" + '\n' + "products/" + key + '\n' + "2018-10-31";
//		byte[] ak = Base64.decode(accessKey);
//		byte[] _sign = strForSign.getBytes();
//		ByteArrayOutputStream tmp2 = new ByteArrayOutputStream();
//		tmp2.writeBytes(ak);
//		tmp2.writeBytes(_sign);
//		String apisign = Base64.encodeToString(Lang.sha1(new ByteArrayInputStream(tmp2.toByteArray())).getBytes(), false);
//
//		headers.set("Authorization", tmp + URLEncoder.encode(apisign, Encoding.CHARSET_UTF8));
//		// System.out.println(strForSign);
//		// System.out.println(headers.get("Authorization"));
//		// System.out.println(headers);
//
//		Response resp = Sender.create(req).send();
//		if (resp.isOK()) {
//			NutMap re = Json.fromJson(NutMap.class, resp.getReader());
//			return new NutMap("secret", re.getAs("data", NutMap.class).getString("key"));
//		} else {
//			log.debug("onenet say no " + resp.getContent());
//		}
//
//		return new NutMap("msg", "server error");
	}
}
